<?php	if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
 * Tokaban Standard System
 *
 * Tokaban framework for PHP
 *
 * @package		ap_standard_system
 * @author		Tokaban R&D Team
 * @copyright	Copyright (c) 2009, Tokaban, Inc. 
 * @since		Version 2.0
 *   
 */ 
   
// ------------------------------------------------------------------------
class order_complete extends Controller 
{	

	var $nid_order				= '';
	var $obj_order				= '';
	var $obj_order_detail		= '';
	// ------------------------------------------------------------------------
	
/** 
 * Constructor
 *
 * Load cac thu vien can su dung cho class 
 *
 * @access	public 
 */	
function order_complete()
	{ 
		// 
		// DINH NGHIA BAT BUOC TRONG TAT CA CAC CONTROLLER.
		// KHONG DUOC TU Y THAY DOI CAC DONG THONG TIN BEN DUOI. 
		//
		parent::Controller();  
		session_start();
		$this->load->database();
		$this->load->helper('ap_db');	
		$this->load->helper('ap_function');
		$this->load->helper('ap_html');
		$this->load->helper('ap_view');
		$this->load->helper('ap_object');
		$this->load->helper('ap_module');
		$this->load->helper('ap_captcha_helper');			
		
		$this->load->model('order_complete_model');	
		$this->load->model('payment_model');
		// 
		// CAC DINH NGHIA CAN THIET KHAC
		// 
	} 
	
	// ------------------------------------------------------------------------
	
/**
 * Goi tuan tu cac ham theo dung quy dinh ve luong du lieu
 * 
 * @access	public
 */		
function index()
	{
		$data['title']			= '';
		$data['tags']			= '';
		$data['description']	= '';
		
		$data['menu_sec']		= '';
		$data['menu_cat']		= '';
		$data['g_ishome']		= 0;
		$this->load->view('order_complete',$data);
	}		
	
	// ------------------------------------------------------------------------

function user($nid_order)
	{
		Funset_userdata('session_nid_customer');
		Funset_userdata('session_customer_name');
		Funset_userdata('session_customer_full_name');
		$data['sec_product'] 		= '';
		$data['cat_product'] 		= '';
		$data['g_ishome']		= 0;
		$this->load->view('ap_payment',$data);
	}

function delete_cart()
	{
		////$this->nid_order		= $nid_order;
//		$this->obj_order 		= $this->order_complete_model->get_byid($this->nid_order);
//		$this->obj_order_detail = $this->order_complete_model->get_order_detail($this->nid_order);
//		
//		$data['obj_order']			=	$this->obj_order;
//		$data['obj_order_detail']	=	$this->obj_order_detail;
		
		Funset_userdata('session_nid_customer');
		Funset_userdata('session_customer_name');
		Funset_userdata('session_customer_full_name');
		unset($_SESSION['cart']);
		
	}

/**
 *-------------------------------------------------------------------
 * @creator 		: Hoang Minh An - an_hm87@tokaban.com

 * @finished date	: 2009/12/13
 * @description		: Insert du lieu vao tcity
 * @access	        : private
 *
 * @param string	: None
 * 					: 
 * @return string	: None
 *-------------------------------------------------------------------
 * @editor   	    : 
 * @finished date	: 
 * @editing content	: 
 *-------------------------------------------------------------------
 */	
function caculator()
	{
		if($this->insert_contact() === TRUE )
		{
			$this->send_mail_order();
			$this->delete_cart();
			redirect(base_url().'complete_cart');
		}
	} 
 	
function insert_contact()
	{

			$data =	array(				
			'cfullname'				=> Fget_userdata('session_customer_full_name'),
			'caddress'				=> Fget_userdata('session_customer_address'),
			'nphone'				=> Fget_userdata('session_customer_phone'),				
			'cemail'				=> Fget_userdata('session_customer_email'),
			'cnote'		    		=> Fget_userdata('session_customer_note'),
			'nid_order_status'		=> 1,
			'ddate01'				=> dbget_current_date(),
			'ddate02'				=> dbget_current_date()
							);
			// Goi phuong thuc cap nhat thong tin vao database.	
			
			$this->payment_model->insert_order($data);
			// Xac dinh gia tri id master sau khi cap nhat.
			$this->nid_order = dbget_identity();
			
			$data =	array(				
			'ccode'				=> 'shop_'.$this->nid_order,
					);
			$this->payment_model->update_bynid($this->nid_order,$data);
			
			if(isset($_SESSION['cart'])):
				foreach($_SESSION['cart'] as $key=>$value): 
				
				$data =	array(				
				'nid_order'				=> $this->nid_order,
				'nid_product'			=> $key,
				'nquantity'				=> $_SESSION['cart'][$key]				
					);
				$this->payment_model->insert_order_detail($data);
				endforeach; 
			endif;		
			return TRUE;
	}


function send_mail_order()
	{
		$content	= '';
		//Thong tin header order
		$obj_data = get_page_news(26);
		foreach($obj_data as $data):
			$content	.= $data['cnote'];	
		endforeach; 
		
		
		$content .=  '<div id="title" style="text-align:center;font-weight:bold;margin:20px 0;">ĐƠN ĐẶT HÀNG ONLINE</div>';
		$content .=  '<p><b>Thông tin khách hàng: </b></p>';
		
		$content .=  '<table border="0" cellpadding="0" cellspacing="1" style="width:98%;background:#CCC;">';
		$content .=  '    <tr>';
		$content .=  '			<td style="width:200px;background:#fff;padding:4px;">Khách hàng</td>';
		$content .=  '			<td style="background:#fff;padding:4px;">'. Fget_userdata('session_customer_full_name').'</td>';
		$content .=  '    </tr>';
		$content .=  ' 	  <tr>';
		$content .=  '			<td style="color:#FF0000;background:#fff;padding:4px;">Địa chỉ giao hàng</td>';
		$content .=  '			<td style="color:#FF0000;background:#fff;padding:4px;">'. Fget_userdata('session_customer_address'). '</td>';
		$content .=  '	  </tr>';
		$content .=  '	  <tr>';
		$content .=  '			<td style="background:#fff;padding:4px;">Điện thoại</td>';
		$content .=  '			<td style="background:#fff;padding:4px;">'.Fget_userdata('session_customer_phone').'</td>';
		$content .=  ' 	  </tr>';
		$content .=  '	  <tr>';
		$content .=  '			<td style="background:#fff;padding:4px;">Email</td>';
		$content .=  '			<td style="background:#fff;padding:4px;">'.Fget_userdata('session_customer_email').'</td>';
		$content .=  '	  </tr>';
		$content .=  '    <tr>';
		$content .=  '			<td style="background:#fff;padding:4px;">Thông tin ghi chú</td>';
		$content .=  '			<td style="background:#fff;padding:4px;">'. Fget_userdata('session_customer_note').'</td>';
		$content .=  '    </tr>';
		$content .=  '</table>';
		
		$content .=  '<p style="margin-top:20px;"><b>Thông tin sản phẩm: </b></p>';
		$content .=  '<table border="0" cellpadding="0" cellspacing="1" style="width:98%;background:#CCC;" >';
		$content .=  '	<thead>';
		$content .=  '		<tr>';
		$content .=  '			<th style="width:70px;background:#EBEBEB;padding:4px;">Mã SP</th>';
		$content .=  '			<th style="background:#EBEBEB;padding:4px;">Tên sản phẩm</th>';
		$content .=  '			<th style="width:80px;background:#EBEBEB;padding:4px;">Số lượng </th>';
		$content .=  '			<th style="width:110px;background:#EBEBEB;padding:4px;">Đơn giá </th>';
		$content .=  '			<th style="width:110px;background:#EBEBEB;padding:4px;">Thành tiền </th>';
		$content .=  '		</tr>';
		$content .=  '	</thead>';
		$content .=  '	<tbody>';
				
			$count = 0;$total = 0;
			if(isset($_SESSION['cart'])):
			foreach($_SESSION['cart'] as $key=>$value): 
			$data	= get_product_byid($key);
			if($data['fprice_sale'] != 0 && $data['fprice_sale'] != '')
				$total += $_SESSION['cart'][$key] * $data['fprice_sale'];
			else
				$total += $_SESSION['cart'][$key] * $data['fprice'];
				
		$content .=  '		<tr class="row'.$count%2 .'">';
		$content .=  '			<td style="background:#fff;padding:4px;">'.$data['ccode'].'</td>';
		$content .=  '			<td style="background:#fff;padding:4px;">'.$data['cproducts'] .'</td>';
		$content .=  '			<td style="background:#fff;padding:4px;">'. $_SESSION['cart'][$key].'</td>';
		if($data['fprice_sale'] != 0 && $data['fprice_sale'] != ''):
			$content .=  '			<td style="background:#fff;padding:4px;text-align:right;padding-right:5px;">'. show_price($data['fprice_sale']).show_price_sale($data['fprice']) .'</td>';
			$content .=  '			<td style="background:#fff;padding:4px;text-align:right;padding-right:5px;">'.number_format($_SESSION['cart'][$key]*$data['fprice_sale']).' VNĐ </td>';
		else:
			$content .=  '			<td style="background:#fff;padding:4px;text-align:right;padding-right:5px;">'. show_price($data['fprice']) .'</td>';
			$content .=  '			<td style="background:#fff;padding:4px;text-align:right;padding-right:5px;">'.number_format($_SESSION['cart'][$key]*$data['fprice']).' VNĐ'.'</td>';
		endif;
		
		$content .=  '		</tr>';
		//$content .=  '		<input type="hidden" name="nid[]" value="'.$data['nid'] .'" />';
				
			$count++;
			endforeach; 
			endif;
				
		$content .=  '		<tr class="row1">';
		$content .=  '			<td colspan="4" style="background:#fff;padding:4px;text-align:right;font-weight:bold;">Tổng số tiền phải thanh toán: </td>';
		$content .=  '			<td style="background:#fff;padding:4px;font-weight:bold;text-align:right;padding-right:5px;">'.number_format($total).' VNĐ' .'</td>';
		$content .=  '		</tr>';
		$content .=  '	</tbody>';
		$content .=  '</table>';
		
		$content .=  '<div style="margin:20px 0 10px 0;"> ';
				$obj_data = get_page_news(27);
				foreach($obj_data as $data):
					$content	.= $data['cnote'];	
				endforeach; 
		$content .=  '</div>';
		
			$email = '';
			$obj_data = get_config_byid(5);
			 foreach($obj_data as $data):
				$email		= $data['cvalue'];
			 endforeach;
			 
			$title_email = '';
			$obj_data = get_config_byid(6);
			 foreach($obj_data as $data):
				$title_email		= $data['cvalue'];
			 endforeach;

		//echo $content;
		$this->SendMail(Fget_userdata('session_customer_email'),$email,$title_email,$content,Fget_userdata('session_customer_full_name'));
		
		
		
	}




function server_parse($socket, $response)
	{
	   $server_response = '';
	   while ( substr($server_response,3,1) != ' ' )
	   {
		  if( !( $server_response = fgets($socket, 256) ) )
		  {
			 echo "Couldn't get mail server response codes";
		  }
	   }
	
	   if( !( substr($server_response, 0, 3) == $response ) )
	   {
		  echo "Ran into problems sending Mail. Response: $server_response";
	   }
	}
	
	/****************************************************************************
	*        Function:                 smtpmail
	*        Description:         This is a functional replacement for php's builtin mail
	*                                                function, that uses smtp.
	*        Usage:                        The usage for this function is identical to that of php's
	*                                                built in mail function.
	****************************************************************************/
	function smtpmail($mail_to, $subject, $message, $headers='',$smtp_host, $smtp_username, $smtp_password, 
	$admin_email)
	{
	
			//
			// Fix any bare linefeeds in the message to make it RFC821 Compliant.
			//
			$message = preg_replace("/(?<!\r)\n/si", "\r\n", $message);
	
			if ($headers != "")
			{
					if(is_array($headers))
					{
							if(sizeof($headers) > 1)
							{
									$headers = join("\r\n", $headers);
							}
							else
							{
									$headers = $headers[0];
							}
					}
					$headers = chop($headers);
	
					//
					// Make sure there are no bare linefeeds in the headers
					//
					$headers = preg_replace("/(?<!\r)\n/si", "\r\n", $headers);
					//
					// Ok this is rather confusing all things considered,
					// but we have to grab bcc and cc headers and treat them differently
					// Something we really didn't take into consideration originally
					//
					$header_array = explode("\r\n", $headers);
					@reset($header_array);
					$headers = "";
					$cc = '';
					$bcc = '';
					while( list(, $header) = each($header_array) )
					{
							if( preg_match("/^cc:/si", $header) )
							{
									$cc = preg_replace("/^cc:(.*)/si", "\\1", $header);
							}
							else if( preg_match("/^bcc:/si", $header ))
							{
									$bcc = preg_replace("/^bcc:(.*)/si", "\\1", $header);
									$header = "";
							}
							$headers .= $header . "\r\n";
					}
					$headers = chop($headers);
					$cc = explode(",", $cc);
					$bcc = explode(",", $bcc);
			}
	
	
			if(trim($mail_to) == "")
			{
					exit();
			}
			if(trim($subject) == "")
			{
					die("No email Subject specified");
			}
	
			$mail_to_array = explode(",", $mail_to);
	
			//
			// Ok we have error checked as much as we can to this point let's get on
			// it already.
			//
			if( !$socket = fsockopen($smtp_host, 25, $errno, $errstr, 20) )
			{
					die("Could not connect to smtp host : $errno : $errstr");
			}
			$this->server_parse($socket, "220");
	
			if( !empty($smtp_username) && !empty($smtp_password) )
			{
					// Send the RFC2554 specified EHLO.
					// This improved as provided by SirSir to accomodate
					// both SMTP AND ESMTP capable servers
					fputs($socket, "EHLO " . $smtp_host . "\r\n");
					server_parse($socket, "250");
	
					fputs($socket, "AUTH LOGIN\r\n");
					server_parse($socket, "334");
					fputs($socket, base64_encode($smtp_username) . "\r\n");
					server_parse($socket, "334");
					fputs($socket, base64_encode($smtp_password) . "\r\n");
					server_parse($socket, "235");
			}
			else
			{
					// Send the RFC821 specified HELO.
					fputs($socket, "HELO " . $smtp_host . "\r\n");
					$this->server_parse($socket, "250");
			}
	
			// From this point onward most server response codes should be 250
			// Specify who the mail is from....
			fputs($socket, "MAIL FROM: <" . $admin_email . ">\r\n");
			$this->server_parse($socket, "250");
	
			// Specify each user to send to and build to header.
			$to_header = "To: ";
			@reset( $mail_to_array );
			while( list( , $mail_to_address ) = each( $mail_to_array ))
			{
					//
					// Add an additional bit of error checking to the To field.
					//
					$mail_to_address = trim($mail_to_address);
					if ( preg_match('/[^ ]+\@[^ ]+/', $mail_to_address) )
					{
							fputs( $socket, "RCPT TO: <$mail_to_address>\r\n" );
							$this->server_parse( $socket, "250" );
					}
					$to_header .= "<$mail_to_address>, ";
			}
			// Ok now do the CC and BCC fields...
			@reset( $bcc );
			while( list( , $bcc_address ) = each( $bcc ))
			{
					//
					// Add an additional bit of error checking to bcc header...
					//
					$bcc_address = trim( $bcc_address );
					if ( preg_match('/[^ ]+\@[^ ]+/', $bcc_address) )
					{
							fputs( $socket, "RCPT TO: <$bcc_address>\r\n" );
							$this->server_parse( $socket, "250" );
					}
			}
			@reset( $cc );
			while( list( , $cc_address ) = each( $cc ))
			{
					//
					// Add an additional bit of error checking to cc header
					//
					$cc_address = trim( $cc_address );
					if ( preg_match('/[^ ]+\@[^ ]+/', $cc_address) )
					{
							fputs($socket, "RCPT TO: <$cc_address>\r\n");
							$this->server_parse($socket, "250");
					}
			}
			// Ok now we tell the server we are ready to start sending data
			fputs($socket, "DATA\r\n");
	
			// This is the last response code we look for until the end of the message.
			$this->server_parse($socket, "354");
	
			// Send the Subject Line...
			fputs($socket, "Subject: $subject\r\n");
	
			// Now the To Header.
			fputs($socket, "$to_header\r\n");
	
			// Now any custom headers....
			fputs($socket, "$headers\r\n\r\n");
	
			// Ok now we are ready for the message...
			fputs($socket, "$message\r\n");
	
			// Ok the all the ingredients are mixed in let's cook this puppy...
			fputs($socket, ".\r\n");
			$this->server_parse($socket, "250");
			// Now tell the server we are done and close the socket...
			fputs($socket, "QUIT\r\n");
			fclose($socket);
	
			return TRUE;
	}
	
	function SendMail($frommail,$tomail,$subject,$message,$fromfullname='')
	{
		  $from= $fromfullname." <".$frommail.">";
		  $headers ="Return-Path: ".$fromfullname." <".$frommail.">\r\n";
		  $headers.="From: $from\nX-Mailer: ".$fromfullname."\r\n";
		  $headers .="Mime-Version: 1.0\r\n";
		  $headers .="Content-type: text/html; charset=utf-8\r\n";
		  $smtp_host ='localhost';
		  $result = $this->smtpmail($tomail,$subject,$message,$headers,$smtp_host, $smtp_username='', $smtp_password='', 
	$admin_email='');
	
	}


// END do_init class
}		
/* End of file do_init.php */
/* Location: controller/do_init.php */